package com.example.teachingMaterial.controller;

import com.example.model.pojo.TeachingMaterial;
import com.example.teachingMaterial.service.TeachingMaterialService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.example.model.common.R;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 教学资料Controller
 * 处理教学资料相关的HTTP请求
 */
@RestController
@RequestMapping("/materials")
@Tag(name = "教学资料管理", description = "教学资料的上传、下载、查询和删除功能")
public class TeachingMaterialController {

    @Autowired
    private TeachingMaterialService teachingMaterialService;

    /**
     * 上传教学资料
     *
     * @param title       资料标题
     * @param description 资料描述
     * @param file        资料文件
     * @param category    资料分类
     * @return 上传结果
     */
    @PostMapping("/upload")
    @Operation(summary = "上传教学资料", description = "教师上传教学资料，需要教师权限")
    @ApiResponse(responseCode = "200", description = "资料上传成功")
    public ResponseEntity<?> uploadMaterial(
            @RequestParam("title") @Parameter(description = "资料标题") String title,
            @RequestParam(value = "description", required = false) @Parameter(description = "资料描述") String description,
            @RequestParam("file") @Parameter(description = "资料文件") MultipartFile file,
            @RequestParam("category") @Parameter(description = "资料分类（1-课程大纲, 2-参考资料, 3-模板文件, 4-其他）") Integer category) throws IOException {
        Map<String, Object> result = teachingMaterialService.uploadMaterial(title, description, file,
                category);
        return ResponseEntity.ok(R.success(result));

    }

    /**
     * 获取教学资料列表
     *
     * @param category 资料分类
     * @param page     页码
     * @param size     每页数量
     * @return 资料列表
     */
    @GetMapping
    @Operation(summary = "获取教学资料列表", description = "分页获取教学资料列表，可按分类筛选")
    @ApiResponse(responseCode = "200", description = "操作成功")
    public ResponseEntity<Map<String, Object>> getMaterialList(
            @RequestParam(value = "category", required = false) @Parameter(description = "资料分类") Integer category,
            @RequestParam(value = "page", defaultValue = "1") @Parameter(description = "页码，默认1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") @Parameter(description = "每页数量，默认10") Integer size) {
        try {
            Map<String, Object> data = teachingMaterialService.getMaterialList(category, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "操作成功");
            response.put("data", data);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "查询失败：" + e.getMessage());
            response.put("data", null);

            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 下载教学资料
     *
     * @param id 资料ID
     * @return 文件流
     */
    @GetMapping("/download/{id}")
    @Operation(summary = "下载教学资料", description = "下载指定的教学资料文件")
    @ApiResponse(responseCode = "200", description = "文件下载成功")
    public ResponseEntity<?> downloadMaterial(@PathVariable @Parameter(description = "资料ID") Integer id) {
        try {
            File file = teachingMaterialService.downloadMaterial(id);
            TeachingMaterial material = teachingMaterialService.getMaterialById(id);

            String fileName = URLEncoder.encode(material.getFileName(), StandardCharsets.UTF_8.toString());

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(file.length())
                    .body(new FileSystemResource(file));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(R.fail(400, "下载失败: " + e.getMessage()));
        }
    }

    /**
     * 删除教学资料
     *
     * @param id 资料ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除教学资料", description = "教师删除已上传的教学资料，仅上传者可删除")
    @ApiResponse(responseCode = "200", description = "资料删除成功")
    public ResponseEntity<Map<String, Object>> deleteMaterial(@PathVariable @Parameter(description = "资料ID") Integer id) {
        try {

            boolean success = teachingMaterialService.deleteMaterial(id);

            if (!success) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 404);
                response.put("message", "资料不存在");
                response.put("data", null);
                return ResponseEntity.status(404).body(response);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "资料删除成功");
            response.put("data", null);

            return ResponseEntity.ok(response);
        } catch (SecurityException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 403);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(403).body(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "删除失败：" + e.getMessage());
            response.put("data", null);
            return ResponseEntity.status(500).body(response);
        }
    }
}